package com.changgou.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    // 定义常量
    private static final String AUTHORIZE_TOKEN = "Authorization";


    @Autowired
   private LoadBalancerClient loadBalancerClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //0.放行一些不需要权限token的微服务或者path
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //放行登录
        //如果是登录、goods等开放的微服务[这里的goods部分开放],则直接放行,这里不做完整演示，完整演示需要设计一套权限系统
        if (URLFilter.notHasAuthorize(path)) {
            //放行
            Mono<Void> filter = chain.filter(exchange);

            return filter;
        }
        //1.首先获取token  token可能存在在(header,cookie以及请求参数上 )
        // 1.1 从请求参数获取token
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        //1.2 从请求头上获取
        if (StringUtils.isEmpty(token)) {
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        }
        //1.3从cookie上获取
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        //依旧拿不到token
        if (StringUtils.isEmpty(token)) {
            ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
            String authUri = serviceInstance.getUri().toString();
           String loginUrl = authUri + "/oauth/login?FROM="+request.getURI().toString();
        //    String loginUrl = "localhost:9001" + "/oauth/login?FROM="+request.getURI().toString();

            response.setStatusCode(HttpStatus.SEE_OTHER);//设置状态码  访问其他
            response.getHeaders().add("Location",loginUrl);

            return response.setComplete();//直接返回
        }


        //2.解析token
        try {
            //JwtUtil.parseJWT(token);
            request.mutate().header(AUTHORIZE_TOKEN,"Bearer "+token);


        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.FORBIDDEN);//设置状态码 无效访问
           return response.setComplete();//直接返回


        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 执行的顺序  (优先级)
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
